﻿
using Dapper;
using HBase;
using System;
using System.Collections.Generic;
using System.Linq;

namespace hCommand {
    public abstract class AbsCoreTaskServer :AbsWMSBaseServer, ICoreTaskServer {


        public List<CoreTaskParam> GetListByTaskId(long taskId) {
            string sql = "select * from Core_task_param where 1=1 and task_Id=@taskId";
            return Connection.Query<CoreTaskParam>(sql ,new { taskId = taskId }).ToList();
        }



        public Page<CoreTask> QueryCoreTaskPage(CoreTaskDto dto) {
            string sql = "select * from Core_task where 1=1 ";
            if( dto.status != 0 ) {
                sql += " AND status = @status ";
            }
            return this.queryPage<CoreTask>(sql ,"id  desc" ,dto);
        }

        public Page<CoreTask> QueryCoreYTaskPage<CoreTask>(CoreTaskDto dto) {
            string sql = "select * from Core_task where buss_Type=4 ";

            if( !string.IsNullOrEmpty(dto.info) ) {
                dto.info = "%" + dto.info + "%";
                sql += " AND info like @info ";
            }
            return this.queryPage<CoreTask>(sql ,"id  desc" ,dto);
        }



        public bool UpdateStatusById(CoreTask model) {
            string sql = "update  Core_task set Status=1 where id=@id";
            Connection.Execute(sql ,new { id = model.id });
            return true;
        }
        public List<CoreTaskParam> getTaskParamByTaskId(long taskId) {
            string sql = "select * from Core_task_param where task_Id=@taskId";
            List<CoreTaskParam> coreTasks = Connection.Query<CoreTaskParam>(sql ,new { taskId = taskId }).AsList();
            return coreTasks;
        }
        public List<CoreTaskParam> getWorkingTaskParam() {

            string sql = "select * from Core_task_param where status=" + ( int ) CoreTaskParamStatus.可以接收任务 + "  order by id ";
            List<CoreTaskParam> coreTasks = Connection.Query<CoreTaskParam>(sql).AsList();
            return coreTasks;
        }

        public void updateTaskParamStatus(long paramId ,CoreTaskParamStatus status) {
            string sql = "update Core_task_param set status=@status where id=@paramId and  status<@status";
            Connection.Execute(sql ,new { status = ( int ) status ,paramId = paramId });
        }

        public List<string> GetUser(string name ,string password) {
            List<string> res = new List<string>();
            String sql = "select id from sys_user where userstatus<>0 and name=@name and passwords=@password";
            List<long> userIdList = Connection.Query<long>(sql ,new { name = name ,password = password }).ToList();
            if( userIdList.Count != 1 ) {
                res.Add("账号异常");
                return res;
            } else {
                res.Add("0");
            }
            return res;
        }
        public virtual List<CoreTask> getfinshTasksforBackUp() {
            string sql = "select * from Core_task where upload=1 and DATEDIFF([hour], Finsh_Time,getDate())>12";
            List<CoreTask> coreTasks = Connection.Query<CoreTask>(sql).AsList();
            return coreTasks;
        }
        public List<CoreTask> getfinshTasksforUpload() {
            string sql = "select * from Core_task where upload=0 and status =9";
            List<CoreTask> coreTasks = Connection.Query<CoreTask>(sql).AsList();
            return coreTasks;
        }
        public virtual List<CoreTask> getfinshTasksforDelete() {


            String sql = "SELECT*  FROM  [Core_task]  where stock_Id=0 and status in(-1,9) and DATEDIFF([hour], Finsh_Time,getDate())>12 ";
            List<CoreTask> coreTasks = Connection.Query<CoreTask>(sql).AsList();
            return coreTasks;
        }
        public void updateedTask(long id) {
            string sql = "update Core_task set upload=1 where id=@id";
            Connection.Execute(sql ,new { id });
        }

        public List<CoreTask> getTasksByStockId(long stockId) {
            string sql = "select * from Core_task where  stock_Id =@stockId";
            List<CoreTask> coreTasks = Connection.Query<CoreTask>(sql ,new { stockId }).AsList();
            return coreTasks;

        }


        void updateCache(String where ,object param) {

            String sql = "select * from Core_Task_Param " + where;

            List<CoreTaskParam> list = Connection.Query<CoreTaskParam>(sql ,param).ToList();
            if( list.Count != 1 ) {
                LoggerCommon.fileAll(list.Count + "更新任务过多" + where + JsonUtil.mySerializeObject(param));
            }

            MyCache.addOver(list[0]);
            splitParam(list[0].id);
        }





        public int updateTaskStatus(TaskStatusPersistence tsp) {
            string sql = "update Core_Task_Param set status=@status {0}  where task_No=@taskNo and status<@status  and c_Task_Name=@taskName";
            if( tsp.status == 9 && tsp.stn > 0 ) {
                sql = String.Format(sql ," ,c_stn=@stn ");
            } else {

                sql = String.Format(sql ," ");
            }
            int c = Connection.Execute(sql ,tsp);



            if( !String.IsNullOrWhiteSpace(tsp.errorInfo) ) {


                CoreTaskParam p = MyCache.queryUnique<CoreTaskParam>((a) => {
                    return a.taskNo == tsp.taskNo && a.type != 9;
                } ,"CompleteParam 过多" + tsp.taskNo);



                CoreTask c1 = getById<CoreTask>(p.taskId);
                String info = c1.info;
                c1.info = info.Substring(0 ,info.LastIndexOf("-") - 1) + "-" + tsp.errorInfo;
                this.updateNotNull(c1);
            }
            updateCache("where task_No=@taskNo and c_Task_Name=@taskName" ,tsp);

            return c;

        }



        public int beginTask(BaseTask bt) {
            string sql = "update Core_Task_Param set status={0} ,c_stn=@src,c_des=@des ,c_Task_Name=@cTaskName where task_No=@taskNo  ";
            sql = String.Format(sql ,( int ) CoreTaskParamStatus.待执行);
            var v = new { bt.taskNo ,bt.src ,cTaskName = bt.GetType().Name ,des = bt.getDes() };
            int sun = Connection.Execute(sql ,v);

            updateCache("where task_No=@taskNo" ,bt);

            return sun;
        }

        public int updateParamAt(long paramId ,int stn) {
            if( LocConfig.isLoc(stn) ) {
                String check = "SELECT *   FROM  [Core_Task_Param]  where (c_des=@stn  or c_Stn=@stn ) and id<>@paramId and status> " + ( int ) CoreTaskParamStatus.删除 + " and status<" + ( int ) CoreTaskParamStatus.执行完成;
                List<CoreTaskParam> list = Connection.Query<CoreTaskParam>(check ,new { stn ,paramId }).ToList();
                if( list.Count > 0 ) {
                    throw new Exception(stn + "站台有任务" + list[0].taskNo);
                }
            }
            string sql = "update Core_Task_Param set status=" + ( int ) CoreTaskParamStatus.执行结束 + " ,c_stn=@stn,c_des=@stn,c_Task_Name='human'  where id=@paramId";

            int c = Connection.Execute(sql ,new { paramId ,stn });
            updateCache(" where id=@paramId" ,new { paramId });

            return c;
        }
        public int updateParamDes(long paramId ,int stn) {
            string sql = "update Core_Task_Param set des=@stn where id=@paramId";

            int c = Connection.Execute(sql ,new { paramId ,stn });
            updateCache(" where id=@paramId" ,new { paramId });

            return c;
        }




        public bool splitParam(long paramId) {

            CoreTaskParam cp = MyCache.getValue<CoreTaskParam>(paramId);

            CoreTask complete = getById<CoreTask>(cp.taskId);

            return PathFacade.splitParam(cp ,complete);

        }



    }
}
